package com.haidechizi.fastadmin.common.xss;

import com.haidechizi.fastadmin.common.exception.BusinessException;
import org.apache.commons.lang.StringUtils;

/**
 * 校验SQL注入工具类
 */
public class SQLFilter {
    public SQLFilter() {
    }

    /**
     * 替换特殊字符
     * <p>
     * 校验SQL注入
     *
     * @param str
     * @return
     */
    public static String sqlInject(String str) {
        if (StringUtils.isBlank(str)) {
            return null;
        } else {
            str = StringUtils.replace(str, "'", "");
            str = StringUtils.replace(str, "\"", "");
            str = StringUtils.replace(str, ";", "");
            str = StringUtils.replace(str, "\\", "");
            str = str.toLowerCase();
            String[] keywords = new String[]{"master", "truncate", "insert", "select", "delete", "update", "declare", "alter", "drop"};
            int length = keywords.length;

            for (int i = 0; i < length; ++i) {
                String keyword = keywords[i];
                if (str.indexOf(keyword) != -1) {
                    throw new BusinessException("包含非法字符");
                }
            }
            return str;
        }
    }
}
